// content.js
(function() {
  const LOG_PREFIX = '[IframePath]';
  let enabled = false;
  let tooltip = null;
  let markers = new Set();

  function log(...args) {
    console.log(LOG_PREFIX, ...args);
  }

  // 安全创建工具提示
  function createTooltip() {
    if (tooltip) return;

    const init = () => {
      if (!document.body) {
        log('文档body未就绪，等待重试...');
        setTimeout(init, 100);
        return;
      }

      log('创建提示工具');
      tooltip = document.createElement('div');
      Object.assign(tooltip.style, {
        position: 'fixed',
        backgroundColor: '#ffeb3b',
        border: '2px solid #000',
        padding: '4px 8px',
        borderRadius: '4px',
        fontSize: '14px',
        fontWeight: 'bold',
        zIndex: '2147483647',
        pointerEvents: 'none',
        display: 'none'
      });
      document.body.appendChild(tooltip);
    };

    if (document.readyState === 'complete') {
      init();
    } else {
      document.addEventListener('DOMContentLoaded', init);
    }
  }

  // 元素标识生成
  function getElementIdentifier(element) {
    if (element.id) return `#${element.id}`;
    if (element.name) return `[name="${element.name}"]`;
    
    const text = element.textContent?.trim().slice(0, 30);
    if (text) return `"${text}${element.textContent.length > 30 ? '...' : ''}"`;
    
    const siblings = Array.from(element.parentElement?.children || []);
    const index = siblings.indexOf(element);
    return `${element.tagName}${index !== -1 ? `:nth-child(${index + 1})` : ''}`;
  }

  // 路径计算
  function getIframePath() {
    const path = [];
    try {
      let win = window;
      while (win !== win.top) {
        const iframes = Array.from(win.parent.document.querySelectorAll('iframe'));
        const index = iframes.findIndex(iframe => {
          try { return iframe.contentWindow === win; } 
          catch { return false; }
        });
        if (index === -1) break;
        path.unshift(index);
        win = win.parent;
      }
    } catch (error) {
      log('路径计算错误:', error);
    }
    return path.join(',') || 'Main';
  }

  // 鼠标事件处理
  function handleMouseMove(e) {
    if (!enabled || !tooltip) return;
    
    try {
      const element = e.target;
      const path = `${getIframePath()} → ${getElementIdentifier(element)}`;
      
      tooltip.textContent = path;
      tooltip.style.display = 'block';
      tooltip.style.left = `${e.clientX + 15}px`;
      tooltip.style.top = `${e.clientY + 15}px`;
    } catch (error) {
      log('鼠标事件处理错误:', error);
    }
  }

  // 消息监听
  chrome.runtime.onMessage.addListener((message) => {
    if (message.enabled !== undefined) {
      enabled = message.enabled;
      if (enabled) {
        createTooltip();
        document.addEventListener('mousemove', handleMouseMove);
      } else {
        document.removeEventListener('mousemove', handleMouseMove);
        if (tooltip) tooltip.style.display = 'none';
      }
    }
  });

  // 初始化
  createTooltip();
  chrome.storage.local.get('enabled', ({ enabled: storedState }) => {
    enabled = storedState;
    if (enabled) document.addEventListener('mousemove', handleMouseMove);
  });
})();